// 函数组件 抢购管理
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message, Collapse } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import { getPurchase, deletePurchase, serchPurchase, deleteS, getCircuits, updateById, findAllGoods } from '../../../api/promotion'
import getSelectTime from '../../../utils/date'
import dayjs from 'dayjs'
//表格数据类型
interface DataType {
  id: number;//序号
  title: string;//名称
  goods: string;//商品名
  goodsId: string;//货号
  state: number;//上下架
  start: string;//开始时间
  creat: string;//添加时间
}
export default function Purchase() {
  const [ModalOpen, setModalOpen] = useState(false);//删除弹框
  const [isModalOpen, setIsModalOpen] = useState(false);//修改弹框
  const [amend, setAmend] = useState(Object);//装修改内容
  const [newamend, setNewamend] = useState(Object)//装修改后的内容
  const [form] = Form.useForm()
  const { Panel } = Collapse;
  const [page, setPage] = useState(1)//页码
  const [pageSize, setPagesize] = useState(5)//一页几条
  const [id, setID] = useState<number>() //id
  const [searchid, setSearchid] = useState<number>() //id
  const [count, setCount] = useState<number>()
  const [options, setOptions] = useState<any>()
  const [data, setData] = useState<DataType[]>();//装表格内容
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [select, setSelect] = useState(Array)
  const [goodsId, setGoodsId] = useState<string>()
  const [switchId,setSwitchId] = useState<number>()
  //表格部分
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
    },
    {
      title: '抢购标题',
      dataIndex: 'title',
    },
    {
      title: '商品',
      dataIndex: 'goods',
    },
    {
      title: '货号',
      dataIndex: 'goodsId',
    },
    {
      title: '是否上架',
      dataIndex: 'state',
      render: (_, record) => (
        <Switch defaultChecked={record.state === 1 ? true : false}
          onChange={onChange}
          onClick={() => { labelChange(record) }}
        />
      ),
    },
    {
      title: '开始时间',
      dataIndex: 'start',
    },
    {
      title: '添加时间',
      dataIndex: 'creat',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" className='edmit' onClick={() => edmit(record)} htmlType="submit">修改</Button>
          <Button id='del' onClick={() => showModal(record)} >删除</Button>
        </Space >
      ),
    },
  ];

  //获取选中的序号
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  //路由跳转
  const navigate = useNavigate()

  //获取页码
  const Change = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPage(page)
    setPagesize(pageSize)
  }

  useEffect(() => {
    getpurchase()
  }, [page, pageSize])


  //上下架状态
  const OnChange = (value: number) => {
    console.log(`selected`, value);
  }

  //获取抢购商品内容
  const getpurchase = () => {
    getPurchase({
      num: page,
      size: pageSize,
    }).then(res => {
      console.log('获取抢购列表', res);
      if (res.code == '200') {
        setData(res.data.all)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('失败', err);
    })


  }

  //添加
  const add = () => {
    navigate('/home/promotion/AddPurchase')
  }

  //查询获取input框内容
  const onFinish = (values: any) => {
    console.log('values', values)
    const date = values.stateTime ? getSelectTime(values.stateTime) : values.stateTime
    serchPurchase({
      num: page,
      size: pageSize,
      time: date,
      state: values.state,
      title: values.keyword
    }).then(res => {
      console.log('查询成功', res);
      if (res.code == '200') {
        setData(res.data.all)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('查询失败', err);
    })
    message.success('查询成功！')
  }

  //重置
  const resetting = () => {
    getpurchase()
    message.success('重置成功！')
  }

  //修改
  useEffect(() => {
    form.setFieldsValue({
      title: amend.title,
      goodsId: amend.goodsId,
      start: dayjs(amend.start),
    })
    // console.log('gengg',amend);
  }, [amend])
  // console.log('gengg', amend);
  //
  const onInput = (changedValues: any, allValues: any) => {
    // console.log("changedValues",changedValues,'allValues',allValues);
    setNewamend(allValues)
  }

  const edmit = (record: any) => {
    setAmend(record)
    setIsModalOpen(true);
    console.log('修改', record);
    setSearchid(record.id)
    findAllGoods(null).then(res => {
      const options = res.data.map((item: { name: any; sernum: any; }) => ({
        value: item.sernum,
        label: item.sernum
      }))
      setOptions(options)
      // console.log(options);

    }).catch(err => {
      console.log('获取所有商品失败', err);
    })
  }

  const ehandleOk = () => {
    setIsModalOpen(false);
    console.log('newamend', newamend);
    const date = newamend.start ? getSelectTime(newamend.start) : newamend.start
    updateById({
      goods: goodsId,
      id: searchid,
      start: date,
      title: newamend.title,
    }).then(res => {
      console.log('修改成功', res);
      if (res.code == '200') {
        getpurchase()
      }
    }).catch(err => {
      console.log('修改失败', err);
    })
    message.success('修改成功！')


  };

  const ehandleCancel = () => {
    setIsModalOpen(false);
  };

  //批量删除
  const deletePurchases = () => {
    console.log('selectedRowKeys', selectedRowKeys);
    deleteS({
      id: selectedRowKeys.length
    }).then(res => {
      console.log('删除成功', res);
      if (res.code == '200') {
        getpurchase()
      }
    }).catch(err => {
      console.log('删除失败', err);
    })
    message.success('删除成功！')

  }

  //删除
  const showModal = (record: any) => {
    setModalOpen(true);
    // console.log('OK', record);
    setID(record.id)
  };

  const handleOk = () => {
    setModalOpen(false);
    deletePurchase({
      id: id
    }).then(res => {
      console.log('删除成功', res);
      if (res.code == '200') {
        getpurchase()
      }
    }).catch(err => {
      console.log('删除失败', err);
    })
    message.success('删除成功！')

  };

  const handleCancel = () => {
    setModalOpen(false);
  };

  //时间状态
  const handleChange = (value: number) => {
    // console.log(`selected ${value}`);
    getPurchase({
      num: page,
      size: pageSize,
      sort: value
    }).then(res => {
      console.log('排序成功', res);
      if (res.code == '200') {
        setData(res.data.all)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('排序失败', err);
    })
    message.success('排序成功！')
  };

  //获取货号状态
  const sernum = (v: string) => {
    setGoodsId(v)
  }

  //启动按钮
  const labelChange = (v: any) => {
    setSwitchId(v.id)
    console.log('v', v);
    getCircuits({
      id: v.id  
    }).then(res => {
      console.log('修改开关成功', res);
      if (res.code == '200') {
        getpurchase()
      }
    }).catch(err => {
      console.log('修改开关失败', err);
    })

  }
  //启动按钮
  const onChange = (record: any) => {
    
  };
  return (
    <div>
      {/* 标题 */}
      <p className="head">抢购管理</p>
      {/* 操作部分 */}
      <Collapse className='collapse' defaultActiveKey={['1']}>
        <Panel header="筛选查询" key="1">
          <div className='operate-wrap'>
            <div className='operate-left'>
              <Form className='operate-left operate-left-item' onFinish={onFinish}>
                <Form.Item label="关键词：" className='operate-left-item' name='keyword'>
                  <Input placeholder="标题关键词" className='search' />
                </Form.Item>
                <Form.Item label='状态：' className='operate-left-item' name='state'>
                  <Select
                    onChange={OnChange}
                    style={{ width: 120 }}
                    allowClear
                    options={[{ value: '0', label: '未上架' }, { value: '1', label: '已上架' }]}
                    className='drop'
                  />
                </Form.Item>
                <Form.Item label='添加时间：' className='operate-left-item' name='stateTime'>
                  <DatePicker showTime />
                </Form.Item>
                <Form.Item>
                  <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
                  <Button className='reset operate-left-item' onClick={resetting} >重置</Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </Panel>
      </Collapse>
      <div className='table'>
        {/* 表格操作 */}
        <div className='operationTable'>
          {/* 排序 */}
          <Form>
            <Form.Item label='排序：' className='operate-left-item' name='state'>
              <Space wrap>
                <Select
                  onChange={handleChange}
                  style={{ width: 120 }}
                  allowClear
                  options={[{ value: '2', label: '按时间倒序' }, { value: '1', label: '按时间顺序' }]}
                  className='drop'
                />
              </Space>
            </Form.Item>
          </Form>
          <Button id='del' className='operate-left-item' onClick={deletePurchases}>批量删除</Button>
          <Button className='add' onClick={add}>添加</Button>
        </div>
        {/* 表格 */}
        <ConfigProvider locale={zh_CN}>
          <Table rowSelection={rowSelection} columns={columns} rowKey={item => item.id} dataSource={data} pagination={{
            position: ['bottomRight'],
            pageSizeOptions: [3, 5, 10, 15],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: Change,
            pageSize: pageSize,
            total: count,
          }} />
        </ConfigProvider>
      </div>
      {/* 删除内容 */}
      <Modal title="提示" open={ModalOpen} onOk={handleOk} onCancel={handleCancel} okText='确定' cancelText='取消'>
        <p>确定要删除该条数据吗？</p>
      </Modal>
      {/* 修改弹框 */}
      <Modal title="修改抢购内容" open={isModalOpen} onOk={ehandleOk} onCancel={ehandleCancel} okText='确定' cancelText='取消'>
        <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          onValuesChange={onInput}
          autoComplete="off"
          form={form}

        >
          <Form.Item label="抢购标题" name='title' rules={[{ required: true, message: '请输入促销标题' }]} initialValue={amend.title}>
            <Input placeholder="请输入抢购标题" />
          </Form.Item>
          <Form.Item label="货号" name='goodsId' rules={[{ required: true, message: '请输入详情' }]} initialValue={amend.goodsId}>
            <Select
              onChange={sernum}
              style={{ width: 120 }}
              allowClear
              options={options}
              className='drop'
            />
          </Form.Item>
          <Form.Item label='开始时间：' className='operate-left-item' name='start' initialValue={amend.start}>
            <DatePicker showTime />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}